<!-- src/views/advertiser/BillList.vue -->
<template>
  <div class="bill-container">
    <el-card class="bill-card">
      <template #header>
        <div class="card-header">
          <span>账单管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索广告名称/设备主"
              prefix-icon="Search"
              clearable
              @clear="handleSearchClear"
              style="width: 220px"
            ></el-input>
            <el-select 
              v-model="filterStatus" 
              placeholder="状态" 
              clearable
              style="width: 120px; margin-left: 10px"
            >
              <el-option label="全部" :value="null"></el-option>
              <el-option label="未支付" value="UNPAID"></el-option>
              <el-option label="已支付" value="PAID"></el-option>
              <el-option label="已逾期" value="OVERDUE"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="billList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="账单ID" width="80"></el-table-column>
        <el-table-column prop="advertisementName" label="广告名称" min-width="150"></el-table-column>
        <el-table-column prop="deviceOwnerName" label="设备主" width="120"></el-table-column>
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getBillStatusType(scope.row.status)">
              {{ getBillStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="支付期限" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.dueDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentDate" label="支付时间" width="160">
          <template #default="scope">
            {{ scope.row.paymentDate ? formatDateTime(scope.row.paymentDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewBillDetail(scope.row.id)"
            >
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'UNPAID'"
              type="success" 
              size="small" 
              @click="viewBillDetail(scope.row.id)"
              :loading="paymentLoading === scope.row.id"
            >
              支付
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getBills, payBill } from '@/api/bill';

const router = useRouter();
const loading = ref(false);
const billList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref('');
const filterStatus = ref(null);
const paymentLoading = ref(null);

// 获取账单列表
const fetchBillList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: filterStatus.value,
      keyword: searchKeyword.value || undefined
    };
    
    const res = await getBills(params);
    if (res.data.code === 200) {
      billList.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.message || '获取账单列表失败');
    }
  } catch (error) {
    console.error('获取账单列表失败', error);
    ElMessage.error('获取账单列表失败');
  } finally {
    loading.value = false;
  }
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchBillList();
};

// 搜索清除
const handleSearchClear = () => {
  searchKeyword.value = '';
  fetchBillList();
};

// 获取账单状态类型
const getBillStatusType = (status) => {
  const statusMap = {
    'UNPAID': 'warning',
    'PAID': 'success',
    'OVERDUE': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取账单状态文本
const getBillStatusText = (status) => {
  const statusMap = {
    'UNPAID': '未支付',
    'PAID': '已支付',
    'OVERDUE': '已逾期'
  };
  return statusMap[status] || '未知';
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 查看账单详情
const viewBillDetail = (id) => {
  router.push({
    path: `/advertiser/bill/${id}`
  });
};

// 支付账单
const handlePayBill = async (id) => {
  try {
    await ElMessageBox.confirm('确定要支付该账单吗？', '支付确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    paymentLoading.value = id;
    const res = await payBill(id);
    if (res.code === 200) {
      ElMessage.success('账单支付成功');
      fetchBillList();
    } else {
      ElMessage.error(res.message || '账单支付失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('账单支付失败', error);
      ElMessage.error('账单支付失败');
    }
  } finally {
    paymentLoading.value = null;
  }
};

// 监听筛选条件变化
watch([searchKeyword, filterStatus], () => {
  currentPage.value = 1;
  fetchBillList();
});

onMounted(() => {
  fetchBillList();
});
</script>

<style scoped>
.bill-container {
  padding: 20px;
}

.bill-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 15px;
}

.el-button {
  margin-left: 0;
  margin-right: 8px;
}

.el-button:last-child {
  margin-right: 0;
}
</style>